package service

import (
	"blog-server/global"
	"blog-server/middleware"
	"blog-server/models"
	"blog-server/models/views"
	"blog-server/utils"
	"blog-server/utils/codes"
	"errors"
)

type UserService struct{}

func NewUserService() *UserService {
	return &UserService{}
}

// UserLogin 用户登录
func (u *UserService) UserLogin(params views.LoginVo) (vo *views.LoginResultVo, err error) {
	var data []models.User
	var result views.LoginResultVo
	err = global.Engine.Table(&models.User{}).Where("username = ? and can_view = true", params.Username).Find(&data)
	if err != nil || len(data) != 1 {
		return nil, errors.New("该用户不存在")
	}
	if err = utils.StructCopy(data[0], &result); err != nil {
		return nil, errors.New("返回数据失败")
	}
	if codes.MD5(params.Password+data[0].Salt) != data[0].Password {
		return nil, errors.New("账号或者密码不正确")
	}
	token, err := middleware.GenToken(data[0])
	if err != nil {
		return nil, errors.New("构造Token失败")
	}
	result.Token = token
	return &result, err
}
